﻿#include "Image.h"
#include <fstream>
#include "GameLib/Framework.h"
using namespace std;

void Image::readFile(char** buffer, int* size, const char* filename) {
	ifstream in(filename, ifstream::binary);
	if (!in) {
		*buffer = 0;
		*size = 0;
	}
	else {
		in.seekg(0, ifstream::end);
		*size = static_cast<int>(in.tellg());
		in.seekg(0, ifstream::beg);
		*buffer = new char[*size];
		in.read(*buffer, *size);
	}
}

unsigned Image::getUnsigned(const char* p) {
	const unsigned char* up;
	up = reinterpret_cast<const unsigned char*>(p);
	unsigned r = up[0];
	r |= up[1] << 8;
	r |= up[2] << 16;
	r |= up[3] << 24;
	return r;
}

Image::Image(const char* filename) {
	// 读取文件时先获取文件的大小
	char* buffer;
	int size = 0;
	readFile(&buffer, &size, filename);

	mHeight = getUnsigned(&(buffer[12]));
	mWidth = getUnsigned(&(buffer[16]));
	mData = new unsigned[mHeight * mWidth];
	for (int i = 0; i < mHeight * mWidth; i++) {
		mData[i] = getUnsigned(&(buffer[i * 4 + 128]));
	}
	delete[] buffer;
	buffer = 0;
}

Image::~Image() {
	delete[] mData;
	mData = 0;
}

int Image::width() const {
	return mWidth;
}

int Image::height() const {
	return mHeight;
}

const unsigned* Image::data() const {
	return mData;
}

void Image::drawCell(int disX, int disY, GameLib::Framework framework) {
	unsigned* vram = framework.videoMemory();
	unsigned windowWidth = framework.width();

	for (int y = 0; y < this->height(); ++y) {
		for (int x = 0; x < this->width(); ++x) {
			vram[(y + disY) * windowWidth + (x + disX)] = (this->mData)[y * this->mWidth + x];
		}
	}
}